﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DDD4Fun.Common
{
    class CEquals
    {
        public static void TestEqual()
        {
            CEqualsPerson p1 = new CEqualsPerson() { IDCode = "1" };
            CEqualsPerson p2 = new CEqualsPerson() { IDCode = "1" };
            CEqualsPerson p3 = new CEqualsPerson() { IDCode = "3" };
            Console.WriteLine("p1 equal? p2 {0}", p1.Equals(p2));
            Console.WriteLine("p1 ==? p2 {0}", p1 == p2);
            Console.WriteLine("p1 equal? p3 {0}", p1.Equals(p3));
        }

    }

    class CEqualsPerson : IEquatable<CEqualsPerson>
    {
        public string IDCode { set; get; }

        public string FirstName { set; get; }

        public string LastName { set; get; }

        public override bool Equals(object obj)
        {
            return IDCode == (obj as CEqualsPerson).IDCode;
        }
        //只重写Equals来进行对象的比较 保留==来表示引用性相等
        #region IEquatable<CEqualsPerson> Members

        public bool Equals(CEqualsPerson other)
        {
            
            return IDCode == other.IDCode;
        }

        #endregion

        //重写equals方法的时候需要重新这个方法，避免在使用类似Dictionary类时候导致一些潜在的bug
        public override int GetHashCode()
        {
            //减少不同类型之间根据字符串生成相同HashCode的概率
            return string.Format(
                "{0}#{1}",
                System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName,
                this.IDCode)
                .GetHashCode();
        }
    }
}
